var express = require('express');
var router = express.Router();
const { login } = require('../controller/users');
const { SuccessModel, ErrorModel } = require('../model/resModel');

// login
router.post('/login', function(req, res, next) {
  const { username, password } = req.body
  const { session } = req
  login(username, password).then(user => {
    if (user.length > 0) {
      const result = new SuccessModel('登陆成功')
      session.username = username
      res.json(result)
      return
    }
    res.json(new ErrorModel('登录失败'))
  }).catch(err => res.json({err}))
});

// login-test
router.get('/login-test', function(req, res, next) {
  const { username } = req.session
  debugger;
  username && res.json(new SuccessModel('已登录'))
  !username && res.json(new ErrorModel('未登录'))
})

// sessionTest
router.get('/session-test', function(req, res, next) {
  const { session } = req
  if (session.isVisit) {
    session.isVisit +=1
    res.send(`<p>第${session.isVisit}次，来此页面</p>`)
  } else {
    session.isVisit = 1
    res.send('欢迎第一次来此页面')
  }
})

module.exports = router;
